package work.comeback.omo.dao.crawler.imp;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.dao.crawler.ICrawler;
import work.comeback.omo.model.movie.MovieTask;
import work.comeback.omo.model.movie.detail.MovieDetail;
import work.comeback.omo.model.movie.detail.MovieDetailData;
import work.comeback.omo.model.movie.info.MovieInfo;
import work.comeback.omo.model.movie.info.MovieVoidData;
import work.comeback.omo.service.MovieService;
import work.comeback.omo.service.imp.MovieServiceImpl;

import java.util.ArrayList;

public class CrawlerImpl implements ICrawler {
    private static final Logger logger = LoggerFactory.getLogger(CrawlerImpl.class);
    private final ArrayList<MovieTask> movies = new ArrayList<>();
    private final MovieService movieImp = new MovieServiceImpl();

    @Override
    public void add(MovieTask... mvs) {
        for (MovieTask mv : mvs) {
            if (!this.movies.add(mv)) {
                logger.warn("add movie error!");
            }
        }
    }

    @Override
    public <T> T parse(Document document, Class<T> classOfT) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        if (document != null) {
            return gson.fromJson(document.text(), classOfT);
        }
        return null;
    }

    @Override
    public void executeTask(String taskId) {
        this.movies.forEach(movieTask -> {
            if (movieTask.getId().equals(taskId)) {
                this.start(movieTask);
            }
        });
    }

    @Override
    public void executeAllTasks() {
        for (MovieTask movieTask : this.movies) {
            this.start(movieTask);
        }
    }

    private void start(MovieTask task) {
        Document document = this.client(task);

        if (document == null) return;
        MovieInfo movieInfo = this.parse(document, MovieInfo.class);

        for (MovieVoidData vod : movieInfo.getList()) {
            System.out.println(vod.getTypeId());
            System.out.println(vod.getVodName());
            System.out.println(vod.getTypeName());
        }

        if (movieImp.getMovieInfo().saveAll(movieInfo.getList())) {
            logger.info("存储成功");
        }

        for (MovieVoidData vod : movieInfo.getList()) {
            String detailUrl = task.getBaseUrl() + task.getDetailPrefix() + vod.getVodId();
            Document detailClient = this.client(detailUrl);
            MovieDetail movieDetail;

            try {
                movieDetail = this.parse(detailClient, MovieDetail.class);
            } catch (Exception e) {
                continue;
            }

            if (movieImp.getMovieDetail().saveAll(movieDetail.getList())) {
                logger.info("存储成功 {}", vod.getVodId());
            }

            for (MovieDetailData vodItem : movieDetail.getList()) {
                System.out.println("Name: " + vodItem.getVodName());
            }
        }
    }

    private Document client(String url) {
        Document doc;
        try {
            org.jsoup.Connection connect = Jsoup.connect(url);
            String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0";
            doc = connect.userAgent(userAgent).get();
        } catch (Exception e) {
            return null;
        }
        return doc;
    }

    private Document client(MovieTask movie) {
        return this.client(movie.getUrl());
    }
}
